package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class ApBehaviorEntryServiceImpl implements ApBehaviorEntryService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public ApBehaviorEntry findByUserIdAndEquipmentId(Integer userId, Integer equipmentId) {
        //TODO 当userId不为空时，使用userId查询 如果查询为空，基于userId创建实体类数据
        if (userId!=null){
            Query query = Query.query(Criteria.where("refId").is(userId)
                    .and("type").is(ApBehaviorEntry.Type.USER.getCode()));
            ApBehaviorEntry apBehaviorEntry = mongoTemplate.findOne(query, ApBehaviorEntry.class);
            if (apBehaviorEntry==null){
                apBehaviorEntry = new ApBehaviorEntry();
                apBehaviorEntry.setType(ApBehaviorEntry.Type.USER.getCode());
                apBehaviorEntry.setRefId(userId);
                apBehaviorEntry.setCreatedTime(new Date());
                mongoTemplate.save(apBehaviorEntry);
            }
            return apBehaviorEntry;
        }
        //todo 判断设备id是否为空，不为空使用equipmentId查询 ，如果查询不存在基于设备id创建实体数据
        if (equipmentId!=null){
            Query query = Query.query(Criteria.where("refId").is(equipmentId)
                    .and("type").is(ApBehaviorEntry.Type.EQUIPMENT.getCode()));
            ApBehaviorEntry apBehaviorEntry = mongoTemplate.findOne(query, ApBehaviorEntry.class);
            if (apBehaviorEntry==null){
                apBehaviorEntry = new ApBehaviorEntry();
                apBehaviorEntry.setRefId(equipmentId);
                apBehaviorEntry.setCreatedTime(new Date());
                mongoTemplate.save(apBehaviorEntry);
            }
        }
        return null;
    }
}
